﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DeviceDebugger.DataAccess
{
    public static class DataHelper
    {
        /// <summary>
        /// 通过反射将DataTable转换为List<T>对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            List<T> ts = new();
            string tempName = string.Empty;

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                PropertyInfo[] props = t.GetType().GetProperties();
                foreach (PropertyInfo pi in props)
                {
                    tempName = pi.Name;

                    if (dt.Columns.Contains(tempName))
                    {
                        var values = dr[tempName];
                        if (values != DBNull.Value)
                            pi.SetValue(t, values);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }
}
